#!/usr/bin/python
# Copyright 2007 Alex K (wtwf.com) All rights reserved.

"""
Parse iCalendar feeds

"""

__author__ = "Alex K (wtwf.com)"

import os
import sys
import cgi
import getopt
import logging
import csv

from icalendar import Calendar, Event

if sys.version_info < (2, 4):
    raise "You probably need python 2.5 or greater"

def usage(code, msg=''):
  if code:
    fd = sys.stderr
  else:
    fd = sys.stdout
  PROGRAM = os.path.basename(sys.argv[0])
  print >> fd, __doc__ % locals()
  if msg:
    print >> fd, msg
  sys.exit(code)

def Clean(word):
  return word.lower().strip("\\,.")

def main():
  """The main function runs the Bookmarks application with the provided
  username and password values.  Authentication credentials are required.
  """
  logging.basicConfig()
  logging.getLogger().setLevel(logging.DEBUG)

  # parse command line options
  try:
    opts, args = getopt.getopt(sys.argv[1:], "foe", ["input=", "output=",
                                                     "show_empty"])
  except getopt.error, msg:
    usage()

  txt = open('2008.ical','rb').read()
  cal = Calendar.from_string(txt)
  words = {}
  miles = {}
  for component in cal.walk():
    if component.name == "VEVENT":
      if "2008" in str(component.get("DTSTART")):
        summary = str(component.get("SUMMARY"))
        try:
          mile = int(summary.split()[0])
          conditions = Clean(summary.split()[2])
          if conditions in ("mtb", "road"):
            if conditions not in miles:
              miles[conditions] = []
            miles[conditions].append(mile)
          else:
            print "unknown conditions: " + conditions
            print component
        except Exception, e:
          print e
          print component
        for word in summary.split():
          word = Clean(word)
          words[word] = words.get(word, 0) + 1

  for conditions, numbers in miles.items():
    print "Total Miles %s: %d (in %d rides)" % (conditions,
                                                sum(numbers), len(numbers))

  print "\nPopular People\n"
  for person in ["jun", "nicole", "solo", "tricia", "emily",
                 "markd", "erin", "davec"]:
    print "%s - %d" % (person, words[person])
  print "\nPopular Words\n"
  words = sorted(words.items(), lambda a, b: b[1] - a[1])
  for word in words:
    if word[1] < 10:
      break
    print "%s - %d" % word


if __name__ == '__main__':
  main()
